import Vue from 'vue';
import App from './App';
import NavColorMixin from '@/mixins/navColor'

Vue.mixin(NavColorMixin)
//Vue.prototype.goto = function(e){
//	$.goto(e.currentTarget.dataset.url)
//};

Vue.config.productionTip = false;// 关闭生产环境提示

Vue.mixin({
  // 分享到好友
  onShareAppMessage: function () {
    return this._sharewx();
  },

  // 分享到朋友圈
  onShareTimeline: function () {
    var sharewxdata = this._sharewx();
    var query = (sharewxdata.path).split('?')[1] + '&seetype=circle';
    return {
      title: sharewxdata.title,
      imageUrl: sharewxdata.imageUrl,
      query: query,
    };
  },

  // 导航栏按钮点击事件
  onNavigationBarButtonTap(e) {
    console.log(e);
    var app = getApp();
    if (e.type == 'home') {
      var nowurl = app._url();
      if (nowurl.indexOf('/admin/') === 0) {
        app.goto('/admin/index/index', 'reLaunch');
      } else {
        app.goto(app.globalData.indexurl, 'reLaunch');
      }
    }
  },

  methods: {
    // 页面跳转
    goto: function (e) {
      getApp().goto(e.currentTarget.dataset.url, e.currentTarget.dataset.opentype);
    },

    // 返回上一页
    goback: function () {
      getApp().goback();
    },

    // 获取菜单索引
    getmenuindex: function (menuindex) {
      this.menuindex = menuindex;
    },

    // 数据加载完成
    loaded: function (obj) {
      if (obj && obj.title && !obj.desc) obj.desc = obj.title;
      var that = this;
      uni.hideLoading();
      uni.stopPullDownRefresh(); // 停止下拉刷新
      var app = getApp();

      // 如果未初始化，先初始化数据
      if (app.globalData.isinit == false) {
        app.get('Index/linked', {}, function () {
          that.isload = true;
          that._sharemp(obj); // 设置分享信息
        });
      } else {
        this.isload = true;
        this._sharemp(obj); // 设置分享信息
      }
    },

    // 获取数据
    getdata: function () {
      var that = this;
      getApp().get('Index/linked', {}, function () {
        that.loaded();
      });
    },

    // 获取当前平台
    getplatform: function () {
      return getApp().globalData.platform;
    },

    // 设置 H5 分享信息
    _sharemp: function (obj) {
      // #ifdef H5
      var app = getApp();
      if (app.globalData.platform != 'mp') return; // 非 H5 平台不处理
      if (!obj) obj = {};
      if (!obj.link) obj.link = app.globalData.pre_url + '/h5/' + app.globalData.aid + '.html#' + this.sharepath();

      var currenturl = '/' + (this.route ? this.route : this.__route__); // 当前页面 URL
      var query = '';
      if (this.opt && this.opt.id) {
        query += '?id=' + this.opt.id;
      } else if (this.opt && this.opt.cid) {
        query += '?cid=' + this.opt.cid;
      } else if (this.opt && this.opt.gid) {
        query += '?gid=' + this.opt.gid;
      } else if (this.opt && this.opt.bid) {
        query += '?bid=' + this.opt.bid;
      }
      var currentfullurl = currenturl + query;

      // 设置分享信息
      var sharelist = app.globalData.initdata.sharelist;
      if (sharelist) {
        for (var i = 0; i < sharelist.length; i++) {
          if (
            (sharelist[i]['is_rootpath'] == 1 && sharelist[i]['indexurl'] == currenturl) ||
            (!sharelist[i]['is_rootpath'] && sharelist[i]['indexurl'] == currentfullurl)
          ) {
            obj.title = sharelist[i].title;
            obj.desc = sharelist[i].desc;
            obj.pic = sharelist[i].pic;
            if (sharelist[i].url) {
              var sharelink = sharelist[i].url;
              if (sharelink.indexOf('/') === 0) {
                sharelink = app.globalData.pre_url + '/h5/' + app.globalData.aid + '.html#' + sharelink;
              }
              if (app.globalData.mid > 0) {
                sharelink += (sharelink.indexOf('?') === -1 ? '?' : '&') + 'pid=' + app.globalData.mid;
              }
              obj.link = sharelink;
            }
          }
        }
      }

      // 使用微信 JS-SDK 设置分享信息
      var jweixin = require('jweixin-module');
      jweixin.ready(function () {
        jweixin.onMenuShareAppMessage({
          title: obj.title || app.globalData.initdata.name,
          desc: obj.desc || app.globalData.initdata.desc,
          link: obj.link || '',
          imgUrl: obj.pic || app.globalData.initdata.logo,
          success: function () {
            obj.callback && obj.callback();
          },
        });
        jweixin.onMenuShareTimeline({
          title: obj.title || app.globalData.initdata.name,
          desc: obj.desc || app.globalData.initdata.desc,
          link: obj.link || '',
          imgUrl: obj.pic || app.globalData.initdata.logo,
          success: function () {
            obj.callback && obj.callback();
          },
        });
      });
      // #endif
    },

    // 设置微信分享信息
    _sharewx: function (obj) {
      if (!obj) obj = {};
      var app = getApp();
      var pages = getCurrentPages(); // 获取加载的页面
      var currentPage = pages[pages.length - 1]; // 获取当前页面的对象
      var currenturl = '/' + (currentPage.route ? currentPage.route : currentPage.__route__); // 当前页面 URL
      var query = '';

      // 根据参数生成查询字符串
      if (this.opt && this.opt.id) {
        query += '?id=' + this.opt.id;
      } else if (this.opt && this.opt.cid) {
        query += '?cid=' + this.opt.cid;
      } else if (this.opt && this.opt.gid) {
        query += '?gid=' + this.opt.gid;
      } else if (this.opt && this.opt.bid) {
        query += '?bid=' + this.opt.bid;
      }
      var currentfullurl = currenturl + query;

      // 设置分享信息
      var sharelist = app.globalData.initdata.sharelist;
      if (sharelist) {
        for (var i = 0; i < sharelist.length; i++) {
          if (
            (sharelist[i]['is_rootpath'] == 1 && sharelist[i]['indexurl'] == currenturl) ||
            (!sharelist[i]['is_rootpath'] && sharelist[i]['indexurl'] == currentfullurl)
          ) {
            obj.title = sharelist[i].title;
            obj.desc = sharelist[i].desc;
            obj.pic = sharelist[i].pic;
            obj.link = sharelist[i].url;
          }
        }
      }

      // 生成分享路径
      if (obj.link) {
        var sharepath = obj.link;
        if (sharepath.indexOf('#') > 0) {
          sharepath = sharepath.split('#')[1];
        }
      } else {
        if (obj.tolink) {
          if (obj.tolink.indexOf('#') > 0) {
            sharepath = obj.tolink.split('#')[1];
          } else {
            sharepath = obj.tolink;
          }
        } else {
          var sharepath = this.sharepath();
        }
      }

      // 设置分享标题和图片
      if (obj.title) {
        var title = obj.title;
      } else {
        var title = app.globalData.initdata.name;
      }
      if (obj.pic) {
        var imgUrl = obj.pic;
      } else {
        var imgUrl = '';
      }

      console.log(sharepath);
      typeof obj.callback == 'function' && obj.callback();
      return {
        title: title,
        path: sharepath,
        imageUrl: imgUrl,
      };
    },

    // 生成分享路径
    sharepath: function () {
      var app = getApp();
      var opt = this.opt;
      var currentpath = '/' + (this.route ? this.route : this.__route__); // 当前页面 URL
      var scene = [];
      for (var i in opt) {
        if (i != 'pid') {
          scene.push(i + '_' + opt[i]);
        }
      }
      console.log(app.globalData.mid);
      if (app.globalData.mid) {
        scene.push('pid_' + app.globalData.mid);
      }
      var scenes = scene.join('-');
      if (scenes) {
        currentpath = currentpath + '?scene=' + scenes + '&t=' + parseInt(new Date().getTime() / 1000);
      }
      return currentpath;
    },

    // 多语言支持
    t: function (text) {
      if (text == 'color1') {
        return getApp().globalData.initdata.color1;
      } else if (text == 'color2') {
        return getApp().globalData.initdata.color2;
      } else if (text == 'color1rgb') {
        var color1rgb = getApp().globalData.initdata.color1rgb;
        return color1rgb['red'] + ',' + color1rgb['green'] + ',' + color1rgb['blue'];
      } else if (text == 'color2rgb') {
        var color2rgb = getApp().globalData.initdata.color2rgb;
        return color2rgb['red'] + ',' + color2rgb['green'] + ',' + color2rgb['blue'];
      } else {
        return getApp().globalData.initdata.textset[text] || text;
      }
    },

    // 判断元素是否在数组中
    inArray: function (search, array) {
      for (var i in array) {
        if (array[i] == search) {
          return true;
        }
      }
      return false;
    },

    // 判断是否为空
    isNull: function (num) {
      return num == undefined || num == 'undefined' || num == null || num == '';
    },

    // 判断数组是否为空
    isEmpty: function (list) {
      return !list || list.length === 0 || (list.length === 1 && (!list[0] || list[0].length === 0));
    },

    // 日期格式化
    dateFormat: function (time, format) {
      if (format == undefined || format == 'undefined' || format == null || format == '') format = 'Y-m-d H:i:s';
      var date = new Date();
      if (time != '' || time > 0) {
        date = new Date(time * 1000);
      }

      var Y = date.getFullYear();
      var m = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
      var d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
      var i = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
      var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      format = format.replace('Y', Y);
      format = format.replace('m', m);
      format = format.replace('d', d);
      format = format.replace('H', H);
      format = format.replace('i', i);
      format = format.replace('s', s);
      return format;
    },

    // 计算两点之间的距离
    getDistance: function (lat1, lng1, lat2, lng2) {
      if (!lat1 || !lng1 || !lat2 || !lng2) return '';
      var rad1 = (lat1 * Math.PI) / 180.0;
      var rad2 = (lat2 * Math.PI) / 180.0;
      var a = rad1 - rad2;
      var b = ((lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0);
      var r = 6378137;
      var juli = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
      juli = juli / 1000;
      juli = juli.toFixed(2);
      return juli;
    },

    // 打开地图
    showMap: function (e) {
      let latitude = parseFloat(e.currentTarget.dataset.latitude);
      let longitude = parseFloat(e.currentTarget.dataset.longitude);
      let scale = e.currentTarget.dataset.scale ? parseInt(e.currentTarget.dataset.scale) : 13;
      let name = e.currentTarget.dataset.name;
      let address = e.currentTarget.dataset.address;
      console.log(latitude);
      console.log(longitude);
      console.log(scale);
      console.log(name);
      console.log(address);
      uni.openLocation({
        latitude: latitude,
        longitude: longitude,
        name: name,
        address: address,
        scale: 13,
      });
    },

    // 预览图片
    previewImage: function (e) {
      var imgurl = e.currentTarget.dataset.url;
      var imgurls = e.currentTarget.dataset.urls;
      if (!imgurls) imgurls = imgurl;
      if (typeof imgurls == 'string') imgurls = imgurls.split(',');
      uni.previewImage({
        current: imgurl,
        urls: imgurls,
      });
    },

    // 复制文本
    copy: function (e) {
      uni.setClipboardData({
        data: e.currentTarget.dataset.text,
        success: function () {
          getApp().error('复制成功');
        },
      });
    },

    // 订阅消息
    subscribeMessage: function (callback) {
      var app = getApp();
      // #ifdef MP-WEIXIN
      var that = this;
      var tmplids = that.tmplids;
      if (tmplids && tmplids.length > 0) {
        uni.requestSubscribeMessage({
          tmplIds: tmplids,
          success: function (res) {
            for (var i in tmplids) {
              if (res[tmplids[i]] == 'accept') {
                app.post('Index/subscribemessage', { tmplid: tmplids[i] }, function () { });
              }
            }
            console.log(res);
            typeof callback == 'function' && callback();
          },
          fail: function (res) {
            console.log(res);
            typeof callback == 'function' && callback();
          },
        });
      } else {
        typeof callback == 'function' && callback();
      }
      // #endif
      // #ifndef MP-WEIXIN
      typeof callback == 'function' && callback();
      // #endif
    },

    //金额判断	
    amountCheck: function (e) {
      console.log('e: ', e);
      if (!e || e <= 0) {
        getApp().error('请输入正确的金额');
        return;
      }

      // 检查小数位数是否超过 2 位
      const amountStr = String(e);
      if (!/^\d+(\.\d{1,2})?$/.test(amountStr)) {
        getApp().error('金额小数位数不能超过 2 位');
        return;
      }

      // 检查金额范围（0.01 元到 5000 元）
      if (e < 0.01 || e > 5000) {
        getApp().error('充值金额必须在 0.01 元到 5000 元之间');
        return;
      }
    }
  },
});


App.mpType = 'app';

const app = new Vue({
  ...App
});
app.$mount();
